/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hello;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Random;
import java.util.Vector;
import javax.microedition.io.Connection;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.m3g.World;

/**
 * @author angela.gomes
 */
public class HelloMIDlet extends MIDlet implements CommandListener {

    private boolean midletPaused = false;
    private Vector descricao = new Vector();

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Command exitCommand;
    private Command avisosCommand;
    private Command backCommand;
    private Command detalhesCommand;
    private Command backtoListCommand;
    private Command sorteioCommand;
    private Form form;
    private ImageItem imageItem;
    private List list;
    private Form sorteioForm;
    private StringItem sorteiostringitem;
    private Image image;
    private Image image1;
    //</editor-fold>//GEN-END:|fields|0|

    /**
     * The HelloMIDlet constructor.
     */
    public HelloMIDlet() {
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getForm());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
    //</editor-fold>//GEN-END:|3-startMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
    //</editor-fold>//GEN-END:|4-resumeMIDlet|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
    //</editor-fold>//GEN-END:|5-switchDisplayable|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == form) {//GEN-BEGIN:|7-commandAction|1|23-preAction
            if (command == avisosCommand) {//GEN-END:|7-commandAction|1|23-preAction
                switchDisplayable(null, getList());//GEN-LINE:|7-commandAction|2|23-postAction
                String url = "http://www1.caixa.gov.br/loterias/loterias/megasena/megasena_pesquisa_new.asp?submeteu=sim&opcao=concurso&txtConcurso=1433";
                try{
                    getList().deleteAll();
                    StreamConnection connection = (StreamConnection) Connector.open(url, Connector.READ_WRITE);
                    Reader in = new InputStreamReader(connection.openInputStream(), "UTF-8");
                    StringBuffer buffer = new StringBuffer();
                    int ch=0;
                    while ((ch=in.read())!=-1){
                        buffer.append((char)ch);
                    }
                    list.append("Numero concurso: "+buffer.toString().substring(0, 4),null);
                    list.append("Prêmio: "+buffer.toString().substring(5,buffer.toString().indexOf("|<")),null);
                    list.append(buffer.toString().substring(44,buffer.toString().indexOf("</li>")),null);
                    list.append(buffer.toString().substring(55, 57),null);
                    list.append(buffer.toString().substring(66, 68),null);
                    list.append(buffer.toString().substring(77, 79),null);
                    list.append(buffer.toString().substring(88, 90),null);
                    list.append(buffer.toString().substring(99, 101),null);
                }catch
                    (IOException error) {
                    Alert mensagem = new Alert ("Falha");
                    mensagem.setString(error.getMessage()); mensagem.setTimeout(3000);
                    getDisplay().setCurrent(mensagem);
                }

            } else if (command == exitCommand) {//GEN-LINE:|7-commandAction|3|19-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|4|19-postAction
             // write post-action user code here
            } else if (command == sorteioCommand) {//GEN-LINE:|7-commandAction|5|45-preAction


                switchDisplayable(null, getSorteioForm());//GEN-LINE:|7-commandAction|6|45-postAction
                Random gerar = new Random();
                String texto="" ;
                  for (int i=0;i<=5;i++){
                       int geranovo = gerar.nextInt(60)+1;
                       texto=texto+" - "+geranovo;

                }
                sorteiostringitem.setText(texto);
            }//GEN-BEGIN:|7-commandAction|7|26-preAction
        } else if (displayable == list) {
            if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|7|26-preAction
                // write pre-action user code here
                listAction();//GEN-LINE:|7-commandAction|8|26-postAction
                // write post-action user code here
            } else if (command == backCommand) {//GEN-LINE:|7-commandAction|9|29-preAction
                // write pre-action user code here
                switchDisplayable(null, getForm());//GEN-LINE:|7-commandAction|10|29-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|11|34-preAction
        } else if (displayable == sorteioForm) {
            if (command == backtoListCommand) {//GEN-END:|7-commandAction|11|34-preAction
                // write pre-action user code here
                switchDisplayable(null, getForm());//GEN-LINE:|7-commandAction|12|34-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|13|7-postCommandAction
        }//GEN-END:|7-commandAction|13|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|14|
    //</editor-fold>//GEN-END:|7-commandAction|14|


    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|18-getter|0|18-preInit
    /**
     * Returns an initiliazed instance of exitCommand component.
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
            exitCommand = new Command("Exit", Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
        }//GEN-BEGIN:|18-getter|2|
        return exitCommand;
    }
    //</editor-fold>//GEN-END:|18-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initiliazed instance of form component.
     * @return the initialized component instance
     */
    public Form getForm() {
        if (form == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            form = new Form("RESULTADOS DA MEGASENA", new Item[] { getImageItem() });//GEN-BEGIN:|14-getter|1|14-postInit
            form.addCommand(getExitCommand());
            form.addCommand(getAvisosCommand());
            form.addCommand(getSorteioCommand());
            form.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit

        }//GEN-BEGIN:|14-getter|2|
        return form;
    }
    //</editor-fold>//GEN-END:|14-getter|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: avisosCommand ">//GEN-BEGIN:|22-getter|0|22-preInit
    /**
     * Returns an initiliazed instance of avisosCommand component.
     * @return the initialized component instance
     */
    public Command getAvisosCommand() {
        if (avisosCommand == null) {//GEN-END:|22-getter|0|22-preInit
            // write pre-init user code here
            avisosCommand = new Command("Sorteio atual", Command.ITEM, 0);//GEN-LINE:|22-getter|1|22-postInit
            // write post-init user code here
        }//GEN-BEGIN:|22-getter|2|
        return avisosCommand;
    }
    //</editor-fold>//GEN-END:|22-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|28-getter|0|28-preInit
    /**
     * Returns an initiliazed instance of backCommand component.
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|28-getter|0|28-preInit
            // write pre-init user code here
            backCommand = new Command("Voltar", Command.BACK, 0);//GEN-LINE:|28-getter|1|28-postInit
            // write post-init user code here
        }//GEN-BEGIN:|28-getter|2|
        return backCommand;
    }
    //</editor-fold>//GEN-END:|28-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: detalhesCommand ">//GEN-BEGIN:|30-getter|0|30-preInit
    /**
     * Returns an initiliazed instance of detalhesCommand component.
     * @return the initialized component instance
     */
    public Command getDetalhesCommand() {
        if (detalhesCommand == null) {//GEN-END:|30-getter|0|30-preInit
            // write pre-init user code here
            detalhesCommand = new Command("Detalhes", Command.ITEM, 0);//GEN-LINE:|30-getter|1|30-postInit
            // write post-init user code here
        }//GEN-BEGIN:|30-getter|2|
        return detalhesCommand;
    }
    //</editor-fold>//GEN-END:|30-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: backtoListCommand ">//GEN-BEGIN:|33-getter|0|33-preInit
    /**
     * Returns an initiliazed instance of backtoListCommand component.
     * @return the initialized component instance
     */
    public Command getBacktoListCommand() {
        if (backtoListCommand == null) {//GEN-END:|33-getter|0|33-preInit
            // write pre-init user code here
            backtoListCommand = new Command("Voltar", Command.ITEM, 0);//GEN-LINE:|33-getter|1|33-postInit
            // write post-init user code here
        }//GEN-BEGIN:|33-getter|2|
        return backtoListCommand;
    }
    //</editor-fold>//GEN-END:|33-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: list ">//GEN-BEGIN:|24-getter|0|24-preInit
    /**
     * Returns an initiliazed instance of list component.
     * @return the initialized component instance
     */
    public List getList() {
        if (list == null) {//GEN-END:|24-getter|0|24-preInit
            // write pre-init user code here
            list = new List("\u00DALTIMO RESULTADO", Choice.IMPLICIT);//GEN-BEGIN:|24-getter|1|24-postInit
            list.addCommand(getBackCommand());
            list.setCommandListener(this);//GEN-END:|24-getter|1|24-postInit
            // write post-init user code here
        }//GEN-BEGIN:|24-getter|2|
        return list;
    }
    //</editor-fold>//GEN-END:|24-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: listAction ">//GEN-BEGIN:|24-action|0|24-preAction
    /**
     * Performs an action assigned to the selected list element in the list component.
     */
    public void listAction() {//GEN-END:|24-action|0|24-preAction
        // enter pre-action user code here
        String __selectedString = getList().getString(getList().getSelectedIndex());//GEN-LINE:|24-action|1|24-postAction
        // enter post-action user code here
    }//GEN-BEGIN:|24-action|2|
    //</editor-fold>//GEN-END:|24-action|2|
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: sorteioForm ">//GEN-BEGIN:|32-getter|0|32-preInit
    /**
     * Returns an initiliazed instance of sorteioForm component.
     * @return the initialized component instance
     */
    public Form getSorteioForm() {
        if (sorteioForm == null) {//GEN-END:|32-getter|0|32-preInit
            // write pre-init user code here
            sorteioForm = new Form("N\u00DAMEROS DA SORTE", new Item[] { getSorteiostringitem() });//GEN-BEGIN:|32-getter|1|32-postInit
            sorteioForm.addCommand(getBacktoListCommand());
            sorteioForm.setCommandListener(this);//GEN-END:|32-getter|1|32-postInit
            // write post-init user code here
        }//GEN-BEGIN:|32-getter|2|
        return sorteioForm;
    }
    //</editor-fold>//GEN-END:|32-getter|2|





    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: image ">//GEN-BEGIN:|42-getter|0|42-preInit
    /**
     * Returns an initiliazed instance of image component.
     * @return the initialized component instance
     */
    public Image getImage() {
        if (image == null) {//GEN-END:|42-getter|0|42-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|42-getter|1|42-@java.io.IOException
                image = Image.createImage("/hello/teste.png");
            } catch (java.io.IOException e) {//GEN-END:|42-getter|1|42-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|42-getter|2|42-postInit
            // write post-init user code here
        }//GEN-BEGIN:|42-getter|3|
        return image;
    }
    //</editor-fold>//GEN-END:|42-getter|3|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: sorteioCommand ">//GEN-BEGIN:|44-getter|0|44-preInit
    /**
     * Returns an initiliazed instance of sorteioCommand component.
     * @return the initialized component instance
     */
    public Command getSorteioCommand() {
        if (sorteioCommand == null) {//GEN-END:|44-getter|0|44-preInit
            // write pre-init user code here
            sorteioCommand = new Command("Tente a Sorte", Command.ITEM, 0);//GEN-LINE:|44-getter|1|44-postInit
            // write post-init user code here
        }//GEN-BEGIN:|44-getter|2|
        return sorteioCommand;
    }
    //</editor-fold>//GEN-END:|44-getter|2|



    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: sorteiostringitem ">//GEN-BEGIN:|49-getter|0|49-preInit
    /**
     * Returns an initiliazed instance of sorteiostringitem component.
     * @return the initialized component instance
     */
    public StringItem getSorteiostringitem() {
        if (sorteiostringitem == null) {//GEN-END:|49-getter|0|49-preInit
            // write pre-init user code here
            sorteiostringitem = new StringItem("", "");//GEN-LINE:|49-getter|1|49-postInit
            // write post-init user code here
        }//GEN-BEGIN:|49-getter|2|
        return sorteiostringitem;
    }
    //</editor-fold>//GEN-END:|49-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: imageItem ">//GEN-BEGIN:|50-getter|0|50-preInit
    /**
     * Returns an initiliazed instance of imageItem component.
     * @return the initialized component instance
     */
    public ImageItem getImageItem() {
        if (imageItem == null) {//GEN-END:|50-getter|0|50-preInit
            // write pre-init user code here
            imageItem = new ImageItem("", getImage1(), ImageItem.LAYOUT_DEFAULT, "<Imagem perdida>", Item.PLAIN);//GEN-LINE:|50-getter|1|50-postInit
            // write post-init user code here
        }//GEN-BEGIN:|50-getter|2|
        return imageItem;
    }
    //</editor-fold>//GEN-END:|50-getter|2|

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: image1 ">//GEN-BEGIN:|51-getter|0|51-preInit
    /**
     * Returns an initiliazed instance of image1 component.
     * @return the initialized component instance
     */
    public Image getImage1() {
        if (image1 == null) {//GEN-END:|51-getter|0|51-preInit
            // write pre-init user code here
            try {//GEN-BEGIN:|51-getter|1|51-@java.io.IOException
                image1 = Image.createImage("/hello/megasena.png");
            } catch (java.io.IOException e) {//GEN-END:|51-getter|1|51-@java.io.IOException
                e.printStackTrace();
            }//GEN-LINE:|51-getter|2|51-postInit
            // write post-init user code here
        }//GEN-BEGIN:|51-getter|3|
        return image1;
    }
    //</editor-fold>//GEN-END:|51-getter|3|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

}
